//
//  Main_PublicityView.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/16.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "MainSubPublicityView.h"

#import "StwxDetailViewController.h"
#import "DocumentDetailViewController.h"

#import "CommonPublicityItemCell.h"

@interface MainSubPublicityView() <UITableViewDelegate, UITableViewDataSource>

/// 模型视图
@property (nonatomic, readonly, strong) MainSubPublicityViewModel* viewModel;

@property (nonatomic, copy) NSArray* tableViews;

//IBOutlet
@property (weak, nonatomic) IBOutlet UIView* tabsView;
@property (weak, nonatomic) IBOutlet UIScrollView* tableScrollView;

@end

@implementation MainSubPublicityView

- (void)bindViewModel:(id)viewModel
{
    MainSubPublicityViewModel* vm = viewModel;
    
    if (!self.viewModel)
    {
        _viewModel = vm;
        
        [self _setup];
    }
    else
    {
    }
}

- (void)reloadAllView
{
    for (UITableView* curTableView in self.tableViews)
    {
        [curTableView reloadData];
    }
}

- (void)_setup
{
    @weakify(self)
    
    [self _setupTabsView];
    
    [self _setupTableScrollView];
}

- (void)_setupTabsView
{
    @weakify(self)
    
    UIButton* hzgsBtn = [self.tabsView viewWithTag:10];
    UIButton* ysgsBtn = [self.tabsView viewWithTag:11];
    
    RACSignal* hzgsBtnTouchSignal = [[hzgsBtn rac_signalForControlEvents:UIControlEventTouchUpInside] map:^id(id value) {
        
        return @0;
    }];
    RACSignal* ysgsBtnTouchSignal = [[ysgsBtn rac_signalForControlEvents:UIControlEventTouchUpInside] map:^id(id value) {
        
        return @1;
    }];
    RACSignal* touchsSignal = [hzgsBtnTouchSignal merge:ysgsBtnTouchSignal];
    
    RAC(self.viewModel, tabIndex) = [touchsSignal replay];
    
    RACSignal* tabIndexChangeSignal = RACObserve(self.viewModel, tabIndex);
    
    RAC(hzgsBtn, enabled) = [[tabIndexChangeSignal replay] map:^id(id value)
                                  {
                                      NSInteger num = [value integerValue];
                                      
                                      return @(num == 1);
                                  }];
    RAC(hzgsBtn, backgroundColor) = [[tabIndexChangeSignal replay] map:^id(id value)
                                          {
                                              NSInteger num = [value integerValue];
                                              
                                              return num==0 ? UIColorHex(#e6ffe1) : UIColorHex(#ffffff);
                                          }];
    
    RAC(ysgsBtn, enabled) = [[tabIndexChangeSignal replay] map:^id(id value)
                                  {
                                      NSInteger num = [value integerValue];
                                      
                                      return @(num == 0);
                                  }];
    RAC(ysgsBtn, backgroundColor) = [[tabIndexChangeSignal replay] map:^id(id value)
                                          {
                                              NSInteger num = [value integerValue];
                                              
                                              return num==1 ? UIColorHex(#e6ffe1) : UIColorHex(#ffffff);
                                          }];
    
    [[tabIndexChangeSignal replay] subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSInteger index = [x integerValue];
         
         [self.tableScrollView scrollRectToVisible:(CGRect) {index*self.frame.size.width, 0, self.frame.size.width, self.frame.size.height - 44.0f - 8.0f} animated:YES];
     }];
    
    self.viewModel.tabIndex = 0;
}

- (void)_setupTableScrollView
{
    @weakify(self);
    
    NSMutableArray* newTableViews = [NSMutableArray array];
    
    NSInteger tCount = self.viewModel.tableVMs.count;
    for (NSInteger index=0; index<tCount; index++)
    {
        PublicityTableViewModel* curTableVM = self.viewModel.tableVMs[index];
        
        [[[[RACObserve(curTableVM, dataSource) distinctUntilChanged] filter:^BOOL(id value) {
            
            return value != nil;
        }] deliverOnMainThread]
         subscribeNext:^(id x) {
             @strongify(self)
             // 刷新数据
             
             NSArray* curArr = x;
             UITableView* curTableView = self.tableViews[index];
             UIImageView* emptyTipView = [curTableView viewWithTag:199];
             emptyTipView.hidden = curArr.count > 0;
             
             [self reloadListData:curTableVM.tag];
         }];
        
        curTableVM.didSelectCommand = curTableVM.selectCmd;
        
        [[curTableVM.selectCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x) {
            @strongify(self)
            
            CommonPublicityItemViewModel* ivm = x;
            
            ArticleListData* aListData = ivm.data;
            
            [self _push2StwxDetailVCByArticleID:aListData.articleID type:aListData.type];
            
            //            ArticleBaseItemViewModel* itemVM = x;
            //
            //            [self _push2Web:itemVM.articleData];
        }];
        
        UITableView* tableView = [[UITableView alloc] initWithFrame:(CGRect){index*self.frame.size.width, 0, self.frame.size.width, self.frame.size.height - 44.0f - 8.0f}];
        tableView.tag = 10 + index;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        tableView.rowHeight = UITableViewAutomaticDimension;
//        tableView.estimatedRowHeight = 100.0f;
        tableView.delegate = self;
        tableView.dataSource = self;
        
        /// 添加加载和刷新控件
        if (curTableVM.shouldPullDownToRefresh) {
            /// 下拉刷新
            [tableView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
                /// 加载下拉刷新的数据
                @strongify(self);
                [self tableViewDidTriggerHeaderRefresh:curTableVM];
            }];
            [tableView.mj_header beginRefreshing];
        }
        
        if (curTableVM.shouldPullUpToLoadMore) {
            /// 上拉加载
            @weakify(self);
            [tableView mh_addFooterRefresh:^(MJRefreshAutoNormalFooter *footer) {
                /// 加载上拉刷新的数据
                @strongify(self);
                [self tableViewDidTriggerFooterRefresh:curTableVM];
            }];
            
            /// 判断一下数据
            [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:curTableVM];
        }
        
#ifdef __IPHONE_11_0
        MHAdjustsScrollViewInsets_Never(tableView);
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
#endif
        
        [tableView mh_registerNibCell:[CommonPublicityItemCell class]];
        
        UIImage* emptyTipImg = MHImageNamed(@"baocuo");
        UIImageView* emptyTipView = [[UIImageView alloc] initWithImage:emptyTipImg];
        emptyTipView.hidden = YES;
        CGPoint centerPoint = (CGPoint) {self.frame.size.width/2.0f, self.frame.size.height/2.0f + 22.0f};
        CGSize viewSize = (CGSize) {100, emptyTipImg.size.height*100/emptyTipImg.size.width};
        emptyTipView.frame = (CGRect) {centerPoint.x - viewSize.width/2.0f, centerPoint.y - viewSize.height/2.0f, viewSize};
        emptyTipView.tag = 199;
        UILabel* tipLabel = [[UILabel alloc] initWithFrame:(CGRect) {16, viewSize.height + 24, viewSize.width, 24}];
        tipLabel.text = @"暂无记录";
        tipLabel.textColor = UIColorHex(#bbbbbb);
        [emptyTipView addSubview:tipLabel];
        [tableView addSubview:emptyTipView];
        
        [self.tableScrollView addSubview:tableView];
        
        [newTableViews addObject:tableView];
    }
    self.tableViews = newTableViews;
    
    self.tableScrollView.contentSize = (CGSize) {tCount*self.frame.size.width, self.frame.size.height - 44.0f - 8.0f};
    self.tableScrollView.pagingEnabled = YES;
    self.tableScrollView.alwaysBounceVertical = NO;
    self.tableScrollView.alwaysBounceHorizontal = NO;
    self.tableScrollView.delegate = self;
}

#pragma mark -- sub class can override it
/// 下拉事件
- (void)tableViewDidTriggerHeaderRefresh:(PublicityTableViewModel*)tableVM
{
    @weakify(self)
    NSDictionary* info = @{@"LoadIndex":@(0)};
    
    [[[tableVM.requestDataCmd
       execute:info]
      deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self)
         tableVM.page = 1;
     } error:^(NSError *error) {
         @strongify(self)
         [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
     } completed:^{
         @strongify(self)
         /// 已经在bindViewModel中添加了对viewModel.dataSource的变化的监听来刷新数据
         [self tableViewDidFinishTriggerHeader:YES reload:NO tableVM:tableVM];
     }];
}

/// 上拉事件
- (void)tableViewDidTriggerFooterRefresh:(PublicityTableViewModel*)tableVM
{
    @weakify(self);
    NSDictionary* info = @{@"LoadIndex":@(tableVM.page)};
    
    [[[tableVM.requestDataCmd
       execute:info]
      deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self)
         tableVM.page += 1;
     } error:^(NSError *error) {
         @strongify(self);
         [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
     } completed:^{
         @strongify(self)
         [self tableViewDidFinishTriggerHeader:NO reload:NO tableVM:tableVM];
     }];
}

/// 刷新完成事件
- (void)tableViewDidFinishTriggerHeader:(BOOL)isHeader reload:(BOOL)reload tableVM:(PublicityTableViewModel*)tableVM
{
    UITableView* findTableView = NULL;
    
    for (UITableView* curTableView in self.tableViews)
    {
        if (curTableView.tag == tableVM.tag)
        {
            findTableView = curTableView;
            
            break;
        }
    }
    
    if (findTableView != NULL)
    {
        __weak MainSubPublicityView *weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (reload) {
                [findTableView reloadData];
            }
            if (isHeader) {
                [findTableView.mj_header endRefreshing];
            }
            else{
                [findTableView.mj_footer endRefreshing];
            }
            /// 最后一页隐藏加载控件
            findTableView.mj_footer.hidden = (tableVM.page>=tableVM.lastPage);
        });
    }
}

- (UIEdgeInsets)contentInset{
    return UIEdgeInsetsMake(64, 0, 0, 0);
}

/// reload tableView data
- (void)reloadListData:(NSInteger)tag
{
    for (UITableView* curTableView in self.tableViews)
    {
        if (curTableView.tag == tag)
        {
            NSLog(@"ReloadData Tag : %d", tag);
            
            for (PublicityTableViewModel* curTVM in self.viewModel.tableVMs)
            {
                if (curTVM.tag == tag)
                {
                    NSLog(@"ReloadData dataSource : %d", curTVM.dataSource.count);
                    
                    break;
                }
            }
            
            [curTableView reloadData];
            
            break;
        }
    }
}

/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    return [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CommonPublicityItemCell class])];
}

/// config  data
- (void)configureCell:(CommonPublicityItemCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(CommonPublicityItemViewModel *)object{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    [cell bindViewModel:object];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    PublicityTableViewModel* curTableVM = NULL;
    for (PublicityTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            curTableVM = curTVM;
            
            break;
        }
    }
    
    if (curTableVM.shouldMultiSections) return curTableVM.dataSource ? curTableVM.dataSource.count : 1;
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    PublicityTableViewModel* curTableVM = NULL;
    for (PublicityTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            curTableVM = curTVM;
            
            break;
        }
    }
    
    if (curTableVM.shouldMultiSections) return [curTableVM.dataSource[section] count];
    
    return curTableVM.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PublicityTableViewModel* findTVM = NULL;
    
    for (PublicityTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            findTVM = curTVM;
            
            break;
        }
    }
    
    Class cellClass = [CommonPublicityItemCell class];
    
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:NSStringFromClass(cellClass) forIndexPath:indexPath];
    
    // fetch object
    id object = nil;
    if (findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.section][indexPath.row];
    if (!findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.row];
    
    /// bind model
    [self configureCell:(CommonPublicityItemCell*)cell atIndexPath:indexPath withObject:(id)object];
    
    return cell;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度

    for (PublicityTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (tableView.tag == curTVM.tag)
        {
            return [curTVM.dataSource[indexPath.row] cellHeight];
        }
    }

    return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // execute commond
    
    for (PublicityTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            [curTVM.didSelectCommand execute:curTVM.dataSource[indexPath.row]];
            
            return;
        }
    }
}

#pragma mark - 跳转
- (void)_push2StwxDetailVCByArticleID:(NSString*)articleID type:(NSInteger)type
{
    if (type == 2)
    {
        DocumentDetailViewModel* vm = [[DocumentDetailViewModel alloc] initWithParams:@{}];
        vm.articleID = articleID;
        DocumentDetailViewController* vc = [[DocumentDetailViewController alloc] initWithViewModel:vm];
        UIViewController* showVC = [UIViewController getCurrentVC];
        
        UINavigationController* navc = showVC.navigationController;
        [navc pushViewController:vc animated:YES];
    }
    else
    {
        StwxDetailViewModel* vm = [[StwxDetailViewModel alloc] initWithParams:@{}];
        vm.articleID = articleID;
        StwxDetailViewController* vc = [[StwxDetailViewController alloc] initWithViewModel:vm];
        UIViewController* showVC = [UIViewController getCurrentVC];
        
        UINavigationController* navc = showVC.navigationController;
        [navc pushViewController:vc animated:YES];
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
